package com.streamer.app.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.streamer.app.R
import com.streamer.app.bean.LotteryBean

class LotterySelectionAdapter(
    private val lotteries: MutableList<LotteryBean>,
    private val onItemClick: (LotteryBean) -> Unit
) : RecyclerView.Adapter<LotterySelectionAdapter.LotteryVH>() {

    private var selectedPosition = -1

    class LotteryVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvLotteryName: TextView = itemView.findViewById(R.id.tv_lottery_name)
        val tvLotteryDesc: TextView = itemView.findViewById(R.id.tv_lottery_desc)
        val ivSelected: ImageView = itemView.findViewById(R.id.iv_selected)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LotteryVH {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_lottery_selection, parent, false)
        return LotteryVH(view)
    }

    override fun onBindViewHolder(holder: LotteryVH, position: Int) {
        val lottery = lotteries[position]
        holder.tvLotteryName.text = lottery.name
        holder.tvLotteryDesc.text = lottery.description
        
        // 设置选中状态
        if (position == selectedPosition) {
            holder.ivSelected.visibility = View.VISIBLE
            holder.ivSelected.setImageResource(R.drawable.view_select_on)
        } else {
            holder.ivSelected.visibility = View.GONE
        }

        holder.itemView.setOnClickListener {
            val previousSelected = selectedPosition
            selectedPosition = position
            notifyItemChanged(previousSelected)
            notifyItemChanged(selectedPosition)
            onItemClick(lottery)
        }
    }

    override fun getItemCount(): Int = lotteries.size

    fun getSelectedLottery(): LotteryBean? {
        return if (selectedPosition >= 0 && selectedPosition < lotteries.size) {
            lotteries[selectedPosition]
        } else null
    }

    fun updateData(newLotteries: List<LotteryBean>) {
        lotteries.clear()
        lotteries.addAll(newLotteries)
        selectedPosition = -1
        notifyDataSetChanged()
    }

    fun filterLotteries(query: String) {
        // 这里可以根据搜索关键词过滤抽奖列表
        // 暂时显示所有数据
        notifyDataSetChanged()
    }
} 